package com.sayice.robotconflict.util

import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager

/**
 * 振动
 *
 * @param pattern 振动模式，[m1, n1, m2, n2] 表示在 m1 毫秒后开始震动, 震动 n1 毫秒, 在 m2 毫秒后开始震动, 震动 n2 毫秒
 * @param repeat 重复次数，-1表示不重复，0表示一直震动
 */
fun Context.vibrate(pattern: LongArray, repeat: Int = -1) {
    val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        (this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
    } else {
        this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1))
    } else {
        vibrator.vibrate(pattern, -1)
    }
}

/**
 * 取消震动
 */
fun Context.cancelVibration() {
    val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        (this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
    } else {
        this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }
    try {
        vibrator.cancel()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}